<?php
if (!defined('ABSPATH')) {
	define( 'ABSPATH', dirname(dirname(__FILE__)) . '/' );
}

require_once ABSPATH . 'dr-config.php';
require_once ABSPATH . DRINC . '/dr-base.php';
require_once ABSPATH . DRINC . '/dr-functions.php';

require_once ABSPATH . DRINC . '/dr-smarty.php';

require_once ABSPATH . DRINC . '/dr-page-check-login.php';

if (isset($_POST['submit'])) {
	$reputation_options = array(
	'question_send',
	'answer_send',
	'comment_send',
	'upvote_send',
	'downvote_send',
	'upvote_get',
	'downvote_get',
	'mark_question',
	'mark_people',
	'mark_tag',
	'marks_get'
	);
	$reputations = array();
	foreach ($reputation_options as $option) {
		$reputations[$option] = isset($_POST[$option]) ? intval($_POST[$option]) : 0;
	}
	$result = dr_update_all_reputations($reputations);
	if (is_array($result)) {
		echo 'An error occur when update reputations.';
		die;
	}
}

$reputations = dr_get_all_reputations();
$smarty->assign('reputations', $reputations);

$smarty->assign('page_title', '积分 - iDaren');
$smarty->display('admin/admin-reputations.tpl');

# ================================== #
# functions
# ================================== #

function dr_get_all_reputations() {
	$posts = array(
		'action' => 'get_reputation_settings',
	);
	$json_result = dr_server_request('dr-app-reputations.php', $posts);

	return json_decode($json_result, true);
}
//echo '<pre>';
//var_dump(dr_get_all_reputations());

function dr_update_all_reputations(array $reputations) {
	$posts = array(
		'action' => 'update_all_reputation_settings',
		'reputation_settings' => json_encode($reputations)
	);
	$json_result = dr_server_request('dr-app-reputations.php', $posts);
	$array_result = json_decode($json_result, true);
	if ($array_result['ret'] === 1) {
		return true;
	} else {
		unset($array_result['ret']);
		return $array_result;
	}
}